const Shape = require("./shape.js")
const Utils = require("./utils.js")
const {CN,PLUGINS,EN,WEB} = require("./constant.js")

module.exports = class DrawText extends Shape{
	constructor($env,$event){
		super($env,$event)
		this.__isInPath = false
		// this.__setting = Utils.assign(this.__setting,{
		// 	r:4
		// })
		this.bind();
	}
	bind(){
		this.baseContext.canvas.addEventListener("click",(e)=>{
			if (!this.isActive) return;
			var pos = {
					x : e.pageX,
			        y : e.pageY
			}
			this.show(pos)
		})
		this.$event.on(EN.input_done,(e)=>{
			if (!this.isActive) return;
			this.inputDone(e)
		})
	}
	inputDone(text){
		if(text)this.draw(text)
		this.clearBaseContext()
		this.baseContext.canvas.classList.remove(CN.show)
	}
	show(pos){
		let p = Utils.assign(this.__setting,this.cvsEvtPos(pos,this.cvs));
		let bc = this.baseContext;
		bc.save()
		bc.fillStyle = WEB.theme
		bc.shadowBlur=10;
		bc.shadowColor=WEB.theme;
		this.drawPoint(p,bc)
		bc.restore()
		this.__steps=p;
		bc.canvas.classList.add(CN.show)
		this.$event.emit(EN.plugin,{name:PLUGINS.input,placeholder:"请输入文字"})
	}
	draw(text){
		let p = this.__steps;
		let ctx = this.ctx;

		p.fillStyle = ctx.fillStyle
		p.text = text
		this.rePaint(p)
		this.emit(EN.update_state,this,p)
	}
	rePaint(p,context){
		let ctx = context||this.ctx;
		ctx.fillStyle = p.fillStyle
		ctx.save()
		ctx.font=this.$env.font;
		let w = ctx.measureText(p.text).width;
		ctx.fillText(p.text,p.x-w/2,p.y+3);
		ctx.restore()
	}
}
